package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.dto.result.ApiResponse;
import com.example.domain.entity.Repair;
import com.example.domain.query.RepairQuery;
import com.example.mapper.RepairMapper;
import com.example.service.IRepairService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 设备报修表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-05-15
 */
@Service
public class RepairServiceImpl extends ServiceImpl<RepairMapper, Repair> implements IRepairService {

    @Autowired
    private IDeviceService deviceService;

    @Override
    public IPage<Repair> pageQuery(RepairQuery query, int pageNum, int pageSize) {
        Page<Repair> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Repair> wrapper = new QueryWrapper<>();
        if (query != null) {
            if (query.getRepairId() != null) {
                wrapper.eq("repair_id", query.getRepairId());
            }
            if (query.getDeviceId() != null) {
                wrapper.eq("device_id", query.getDeviceId());
            }
            if (query.getDeptId() != null) {
                wrapper.eq("dept_id", query.getDeptId());
            }
            if (StringUtils.hasText(query.getFaultDescription())) {
                wrapper.like("fault_description", query.getFaultDescription());
            }
            if (query.getAuditStatus() != null) {
                wrapper.eq("audit_status", query.getAuditStatus());
            }
            if (StringUtils.hasText(query.getRepairResult())) {
                wrapper.like("repair_result", query.getRepairResult());
            }
            if (query.getIsScrapped() != null) {
                wrapper.eq("is_scrapped", query.getIsScrapped());
            }
            if (query.getScrapAuditStatus() != null) {
                wrapper.eq("scrap_audit_status", query.getScrapAuditStatus());
            }
            if (query.getCreateStartTime() != null && query.getCreateEndTime() != null) {
                wrapper.between("create_time", query.getCreateStartTime(), query.getCreateEndTime());
            }
        }
        return this.page(page, wrapper);
    }

    @Override
    public boolean addRepair(Repair repair) {
        return this.save(repair);
    }

    @Override
    public boolean updateRepair(Repair repair) {
        return this.updateById(repair);
    }

    @Override
    public boolean deleteRepair(Integer repairId) {
        return this.removeById(repairId);
    }

    @Override
    public ApiResponse scrapAudit(Integer repairId, Integer audit, String auditComment, String repairPlan) {
        // 1. 根据报修ID查找报修记录
        Repair repair = this.getById(repairId);
        if (repair == null) {
            return ApiResponse.error("报修记录不存在");
        }

        // 2. 更新报废审核状态、审核意见和维修计划
        repair.setScrapAuditStatus(audit);
        repair.setAuditComment(auditComment);
        repair.setRepairPlan(repairPlan);
        boolean updateRepairSuccess = this.updateById(repair);

        if (!updateRepairSuccess) {
            return ApiResponse.error("更新报修记录失败");
        }

        // 3. 如果审核通过（audit=1），则查找关联的设备记录并将其状态更新为“报废”
        if (audit != null && audit == 1) {
            // Assuming there is a DeviceService and Device entity to update device status
            // You might need to inject DeviceService here or use a direct mapper call
            // For demonstration, let's assume a method to update device status exists
            // Example: deviceService.updateDeviceStatus(repair.getDeviceId(), "报废");
            // Note: This part requires actual implementation based on your project structure
            // and the Device entity/service.
            // Placeholder for device status update logic
            // For now, we'll just return success if repair update was successful
            // Update device status to "报废"
            boolean updateDeviceSuccess = deviceService.updateDeviceStatus(repair.getDeviceId(), "报废");
            if (!updateDeviceSuccess) {
                 // It might be better to handle this error more gracefully, maybe rollback repair update
                 return ApiResponse.error("更新设备状态失败");
            }
        }

        return ApiResponse.success("报废审核完成");
    }
}
